const config=require('../config/config');
const router=require('koa-router')();
const {User,Post,Comment,Message,Auth}=require('../models/index');
const events=require('events');
const moment=require('moment');
const request=require('request-promise');
const checkPage=require('../middlewares/checkPage');
const checkId=require('../middlewares/checkId');
const {post:postProxy}=require('../proxy/index');
const Page=require('../lib/page');
moment.locale('zh-cn');

//用户详情
router.get('/:id',checkId(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session;

    let user=await User.findOne({_id:id},{password:false,__v:false});
    if(!user)return ctx.flash={error:'用户已删除或不存在'},ctx.redirect('back');

    let auth=await Auth.findOne({user:user._id});
    if(auth){    
        let refreshRes=await request({
            uri:`${config.auth.baseUri}/refresh`,
            qs:{
                refresh_token:auth.refresh_token,
                client_id:config.auth.client_id,
                grant_type:'authorization_code',
                scope:config.auth.scope
            },
            json:true
        });
        if(!refreshRes.error){
            let updateTokenRet=await Auth.update({user},{access_token:refreshRes.access_token,refresh_token:refreshRes.refresh_token});
            console.log('updateTokenRet:',updateTokenRet);
        }
    }

    let [topics,repliesIds]=await Promise.all([
        Post.page({author:user._id},{title:true,time:true},{limit:5}),//最近创建
        Comment.find({author:user._id},{post:true},{sort:{time:-1}})//参与的话题
    ]);
    topics.more=topics.total>1;
    repliesIds=repliesIds.map(post=>post.post);

    let replies=await Post.page({_id:{$in:repliesIds}},{title:true,time:true},{limit:5})
    replies.more=replies.total>1;

    await ctx.render('user',{
        title:'个人信息',
        loginUser,
        user,
        topics,
        replies,
        isSelf:loginUser&&loginUser._id===user._id.toString(),
        messages:ctx.state.messages,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});

//收藏的话题
router.get('/:id/collections',checkId(),checkPage(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session;

    let user=await User.findOne({_id:id},{password:false,__v:false});
    if(!user)return ctx.flash={error:'用户已删除或不存在'},ctx.redirect('back');

    let isSelf=loginUser&&loginUser._id.toString()===user._id.toString();
    if(!isSelf)return ctx.flash={error:'非法操作'},ctx.redirect('back');

    let {collections}=user;
    let {total,page,posts}=await postProxy.getList({_id:{$in:collections}},null,{page:ctx.query.p});

    await ctx.render('userPostList',{
        title:'收藏的话题',
        loginUser,
        success:ctx.flash.success,
        error:ctx.flash.error,
        posts,
        page:Page(ctx.query,page,total)
    });
});

//消息
router.get('/:id/messages',checkId(),checkPage(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session;

    let user=await User.findOne({_id:id},{_id:true});
    if(!user)return ctx.flash={error:'用户已删除或不存在'},ctx.redirect('back');

    let isSelf=loginUser&&loginUser._id.toString()===user._id.toString();
    if(!isSelf)return ctx.flash={error:'非法操作'},ctx.redirect('back');

    let rets=await Promise.all([
        Message.find({to:user._id,read:false}),
        Message.find({to:user._id,read:true})
    ]);

    rets.forEach(ret=>{
        ret.list=ret.map(msg=>{
           var title;
           if('reply'==msg.action){
               title=`<a href="/user/${msg.from._id}">${msg.from.name}</a> 评论了你的话题 <a href="/article/${msg.post._id}#${msg.commentId}">${msg.post.title}</a>`;
           }else if('at'==msg.action){
               title=`<a href="/user/${msg.from._id}">${msg.from.name}</a> 在话题 <a href="/article/${msg.post._id}#${msg.commentId}">${msg.post.title}</a> 中@了你`;
           }
           return {
               title,
               ago:moment(msg.time).fromNow()
           };
        });
    });
    await Message.update({read:false},{$set:{read:true}},{multi:true});
    await ctx.render('messages',{
        title:'消息',
        loginUser,
        unread:{list:rets[0].list},
        read:{list:rets[1].list},
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});


//Public:创建的话题
router.get('/:id/topics',checkId(),checkPage(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session;

    let user=await User.findOne({_id:id},{password:false,__v:false});
    if(!user)return ctx.flash={error:'用户已删除或不存在'},ctx.redirect('back');

    let {total,page,posts}=await postProxy.getList({author:id},null,{limit:5,page:ctx.query.p});

    await ctx.render('userPostList',{
        title:'创建的话题',
        loginUser,
        user,
        isSelf:loginUser&&loginUser._id===user._id.toString(),
        success:ctx.flash.success,
        error:ctx.flash.error,
        posts,
        page:Page(ctx.query,page,total)
    });
});


//Public:参与的话题
router.get('/:id/replies',checkId(),checkPage(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session;

    let [user,repliesIds]=await Promise.all([
        User.findOne({_id:id}),
        Comment.find({author:id},{post:true})
    ]);

    if(!user)return ctx.flash={error:'用户已删除或不存在'},ctx.redirect('back');

    repliesIds=repliesIds.map(reply=>reply.post);
    let {total,page,posts}=await postProxy.getList({_id:{$in:repliesIds}},null,{limit:5,page:ctx.query.p})

    await ctx.render('userPostList',{
        title:'参与的话题',
        loginUser,
        user,
        isSelf:loginUser._id==user._id.toString(),
        posts,
        success:ctx.flash.success,
        error:ctx.flash.error,
        page:Page(ctx.query,page,total)
    });
});

module.exports=router;